<template>
  <div class="container">
    <div class="app-container">
      <!-- 操作栏 -->
      <div class="role-operate" style="display: flex; justify-content: space-between; align-items: center">
        <div style="display: flex; align-items: center">
          <!-- 监测点选择器 -->
          <el-select
            v-model="currentMeasurePoint"
            placeholder="请选择监测点"
            size="mini"
            style="width: 300px; margin-right: 10px"
            @change="handleMeasurePointChange"
          >
            <el-option
              v-for="point in measurePoints"
              :key="point.id"
              :label="point.measurePointName"
              :value="point.id"
            />
          </el-select>

          <input ref="fileInput" type="file" hidden accept=".xls,.xlsx" @change="handleFileChange" />
          <el-button size="mini" type="primary" @click="triggerUpload">上传Excel导入</el-button>
        </div>
        <div style="display: flex; align-items: center">
          <el-input
            v-model="searchTime"
            placeholder="请输入时间查询(如:2012/12)"
            size="mini"
            style="width: 200px; margin-right: 10px"
            clearable
            @keyup.enter.native="handleSearch"
          />
          <el-button size="mini" type="primary" @click="handleSearch">查询</el-button>
        </div>
      </div>

      <!-- 监测点信息 -->
      <div v-if="currentMeasurePointObj" class="measure-point-info">
        <div><strong>监测点名称：</strong>{{ currentMeasurePointObj.measurePointName }}</div>
        <div><strong>监测点编码：</strong>{{ currentMeasurePointObj.measurePointCode }}</div>
        <div><strong>监测点位置：</strong>{{ currentMeasurePointObj.measurePointPosition }}</div>
      </div>

      <!-- 数据表格 -->
      <el-table :data="waterData" v-loading="loading">
        <el-table-column prop="time" align="center" label="时间" sortable>
          <template v-slot="{ row }">
            <span>{{ row.time }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="water_inflow" align="center" label="涌水量（m³/h）">
          <template v-slot="{ row }">
            <span>{{ row.water_inflow }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="200">
          <template v-slot="{ row }">
            <el-button
              size="mini"
              type="text"
              @click="handleEdit(row)"
            >编辑</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 编辑弹窗 -->
      <el-dialog width="500px" title="编辑涌水量" :visible.sync="showEditDialog" @close="cancelEdit">
        <el-form ref="editForm" :model="currentEdit" :rules="formRules">
          <el-form-item label="时间" prop="time" hidden="true">
            <el-date-picker
              v-model="currentEdit.time"
              type="month"
              value-format="yyyy/MM"
              placeholder="选择年月"
            />
          </el-form-item>
          <el-form-item label="涌水量（m³/h）" prop="water_inflow">
            <el-input v-model="currentEdit.water_inflow" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitEdit">确定</el-button>
            <el-button @click="cancelEdit">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'MineWaterInflow',
  data() {
    return {
      loading: false, // 加载状态
      measurePoints: [], // 监测点列表
      currentMeasurePoint: null, // 当前选中的监测点ID
      currentMeasurePointObj: null, // 当前选中的监测点对象
      allWaterData: {}, // 所有监测点的涌水量数据
      searchTime: '',
      waterData: [],
      showEditDialog: false,
      currentEdit: {
        id: null,
        time: '',
        water_inflow: null
      },
      formRules: {
        // 表单验证规则
        water_inflow: [
          { required: true, message: '请输入涌水量', trigger: 'blur' },
          { pattern: /^\d+(\.\d+)?$/, message: '必须为数字值' }
        ]
      }
    }
  },
  created() {
    this.fetchMeasurePoints()
  },
  methods: {
    // 获取监测点列表
    async fetchMeasurePoints() {
      try {
        this.loading = true
        const res = await axios.get('http://localhost:8080/measure-point/getAll')
        if (res.data.code === '0') {
          this.measurePoints = res.data.data
          // 默认选择第一个监测点
          if (this.measurePoints.length > 0) {
            this.currentMeasurePoint = this.measurePoints[0].id
            this.currentMeasurePointObj = this.measurePoints[0]
            // 获取所有涌水量数据
            this.fetchAllWaterData()
          }
        } else {
          this.$message.error(res.data.msg || '获取监测点失败')
        }
      } catch (error) {
        this.$message.error('监测点获取失败')
      } finally {
        this.loading = false
      }
    },

    // 获取所有监测点的涌水量数据
    async fetchAllWaterData() {
      try {
        this.loading = true
        const res = await axios.get('http://localhost:8080/mine-water-inflow/getsGroup')
        if (res.data.code === '0') {
          this.allWaterData = res.data.data
          // 设置当前监测点的数据
          this.setCurrentWaterData()
        } else {
          this.$message.error(res.data.msg || '数据获取失败')
        }
      } catch (error) {
        this.$message.error('涌水量数据获取失败')
      } finally {
        this.loading = false
      }
    },

    // 设置当前监测点的数据
    setCurrentWaterData() {
      if (!this.currentMeasurePointObj) return

      const pointName = this.currentMeasurePointObj.measurePointName
      if (this.allWaterData[pointName]) {
        this.waterData = [...this.allWaterData[pointName]]
          .sort((a, b) => new Date(b.time) - new Date(a.time))
      } else {
        this.waterData = []
        this.$message.warning('该监测点暂无涌水量数据')
      }
    },

    // 处理监测点变更
    handleMeasurePointChange(pointId) {
      this.currentMeasurePointObj = this.measurePoints.find(p => p.id === pointId)
      this.setCurrentWaterData()
    },

    // 触发文件选择
    triggerUpload() {
      this.$refs.fileInput.click()
    },

    // 处理文件上传
    async handleFileChange(e) {
      const file = e.target.files[0]
      if (!file) return

      const formData = new FormData()
      formData.append('file', file)

      try {
        const res = await axios.post(
          'http://localhost:8080/mine-water-inflow/uploadExcel',
          formData,
          { headers: { 'Content-Type': 'multipart/form-data' }}
        )
        if (res.data.success) {
          this.$message.success('上传成功')
          // 重新获取数据
          this.fetchAllWaterData()
        }
      } catch (error) {
        this.$message.error('上传失败')
      } finally {
        this.$refs.fileInput.value = ''
      }
    },

    // 条件查询
    handleSearch() {
      if (!this.searchTime) {
        this.setCurrentWaterData()
        return
      }

      if (this.waterData.length === 0) return

      // 前端过滤数据
      this.waterData = [...this.allWaterData[this.currentMeasurePointObj.measurePointName]]
        .filter(item => item.time.includes(this.searchTime))
        .sort((a, b) => new Date(b.time) - new Date(a.time))
    },

    // 打开编辑弹窗
    handleEdit(row) {
      this.currentEdit = { ...row }
      this.showEditDialog = true
    },

    // 提交编辑
    async submitEdit() {
      try {
        // 注意：这里需要根据实际接口调整参数
        await axios.post(
          `http://localhost:8080/mine-water-inflow/update`,
          {
            ...this.currentEdit,
            measurePointName: this.currentMeasurePointObj.measurePointName
          }
        )
        this.$message.success('更新成功')
        // 刷新当前数据
        this.fetchAllWaterData()
        this.showEditDialog = false
      } catch (error) {
        this.$message.error('更新失败')
      }
    },

    // 取消编辑
    cancelEdit() {
      this.showEditDialog = false
      this.$refs.editForm && this.$refs.editForm.resetFields()
    }
  }
}
</script>

<style scoped>
.role-operate {
  padding: 10px;
  margin-bottom: 20px;
}

.measure-point-info {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border-left: 4px solid #409EFF;
}

.measure-point-info div {
  margin-bottom: 8px;
  font-size: 14px;
}

.measure-point-info div:last-child {
  margin-bottom: 0;
}
</style>
